import React, { Component } from 'react'
import { Input, Button, Row, Col, message } from 'antd'
import * as onlineCoding from '../../constant/online-coding-request-status'
import '../../less/index.less'
import { TwsReactMarkdownPreview } from 'tws-antd'
import AceEditor from 'react-ace'

import 'brace/theme/monokai'

const languages = [
  'javascript',
  'java',
  'python',
  'xml',
  'ruby',
  'sass',
  'markdown',
  'mysql',
  'json',
  'html',
  'handlebars',
  'golang',
  'csharp',
  'elixir',
  'typescript',
  'css'
]

languages.forEach((lang) => {
  require(`brace/mode/${lang}`)
  require(`brace/snippets/${lang}`)
})

const TIMEOUT = 3000

export default class OnlineCodingQuiz extends Component {
  constructor (props) {
    super(props)
    this.state = {
      userAnswerCode: props.quiz.userAnswer,
      language: props.quiz.language,
      loading: false,
      runningResult: props.runningLogs.result,
      status: props.runningLogs.status,
      submissionId: 0
    }

    this.onChange = this.onChange.bind(this)
  }

  buildSubmitData (userAnswerCode, language) {
    const {assignmentId, quiz} = this.props
    return {
      assignmentId,
      name: quiz.onlineCodingName,
      userAnswerCode: this.state.userAnswerCode || userAnswerCode,
      language: language
    }
  }

  submit () {
    const userAnswerCode = this.state.userAnswerCode
    const language = this.state.language
    this.setState({runningResult: ''})

    const data = this.buildSubmitData(userAnswerCode, language)
    this.props.submitAnswer(data, (submissionId) => this.loadLogs(submissionId))
  }

  getResult (status) {
    return status === onlineCoding.status.SUCCESS ? message.success('编译通过') : message.error('编译不通过')
  }

  loadLogs (submissionId) {
    const {assignmentId, quiz, taskId} = this.props
    this.props.getRunningLogs(taskId, assignmentId, quiz.id, submissionId, (result) => {
      const status = result.status
      const logs = result.logs
      this.setState({runningResult: logs, status: status, loading: true})

      if (status !== onlineCoding.status.SUCCESS && status !== onlineCoding.status.ERROR) {
        setTimeout(() => {
          this.loadLogs(submissionId)
        }, TIMEOUT)
      } else {
        this.getResult(status)
        this.setState({loading: false})
      }
    })
  }

  onChange (newValue) {
    this.setState({
      userAnswerCode: newValue
    })
  }

  getRunningResult () {
    const status = this.state.status
    const textResult = onlineCoding.result[status]

    return (<div className={(this.state.status || this.state.status === 0) ? '' : 'hidden'}>
      <label>运行结果为:{textResult}</label>
      <div className='result-content'>
        {this.state.runningResult}
      </div>
    </div>)
  }

  shouldComponentUpdate (nextProps, nextState) {
    return (this.state.userAnswerCode === nextState.userAnswerCode)
  }

  render () {
    const {loading, userAnswerCode, language} = this.state
    const {quiz} = this.props
    const userAnswer = quiz.userAnswer
    const isFinished = userAnswer !== ''
    const disable = this.props.isInstructor ? true : ''
    const codeEditor = <AceEditor
      mode={language}
      theme='monokai'
      onChange={disable ? '' : this.onChange}
      fontSize={14}
      width={'100%'}
      showPrintMargin
      showGutter
      highlightActiveLine
      value={userAnswerCode}
      setOptions={{
        enableBasicAutocompletion: false,
        enableLiveAutocompletion: true,
        enableSnippets: false,
        showLineNumbers: true,
        tabSize: 2
      }} />
    const unSubmitted = <div><h3>提交作业</h3>
      <div className='margin-t-2 mark-down-wrap'>
        <div style={{background: 'white', margin: '-7px 0px 0px 0px'}}>
          <Row>
            <Col span={24} className='margin-l-2'>
              {codeEditor}
            </Col>
          </Row>
          <Row>
            <Col className='margin-t-2 margin-l-2 margin-b-1'>
              <Button style={{width: 250}} disabled={disable} loading={loading}
                onClick={this.submit.bind(this)}>提交代码</Button>
              <p>编程题正在运行时请勿刷新该页面</p>
            </Col>
          </Row>
        </div>
        {this.getRunningResult()}
      </div>
    </div>
    const submitted = <div><h3>我的答案</h3>
      {this.props.preview
        ? <a href={userAnswerCode} target='_blank'>{userAnswerCode}</a>
        : <div className='margin-t-2 mark-down-wrap'>
          <div style={{background: 'white', margin: '-7px 0px 0px 0px'}}>
            <Row>
              <Col span={24} className='margin-l-2'>
                {codeEditor}
              </Col>
            </Row>
            <Row>
              <Col className='margin-t-2 margin-l-2 margin-b-1'>
                <Button style={{width: 250}} loading={loading} disabled={disable}
                  onClick={this.submit.bind(this)}>再次提交代码</Button>
                <p>编程题正在运行时请勿刷新该页面</p>
              </Col>
            </Row>
          </div>
          {this.getRunningResult()}
        </div>}
    </div>

    return <div>
      <div className='margin-t-3'>
        <h3>作业内容</h3>
        <div className='margin-t-2 mark-down-wrap'>
          <TwsReactMarkdownPreview source={quiz ? quiz.description : ''} />
        </div>
      </div>
      <div className='margin-t-3'>
        {this.props.isInstructor ? unSubmitted
          : this.props.isExcellence ? <div>
            <h3>优秀答案</h3>
            <div className='margin-t-2 mark-down-wrap'>
              {codeEditor}
            </div>
          </div>
            : this.props.isTutor ? <div>
              <h3>学生答案</h3>
              <div className='margin-t-2 mark-down-wrap'>
                {isFinished ? <TwsReactMarkdownPreview source={quiz.userAnswer} />
                  : '学生还没有提交答案'}
              </div>
            </div>
              : isFinished ? submitted : unSubmitted
        }
      </div>
    </div>
  }
}
